import Flutter
import UIKit
import Foundation
import AVFoundation

public class FlutterSpectrumPlugin: NSObject, FlutterPlugin, AudioPCMPlayerDelegate {
    var eventSink: FlutterEventSink?
    var playCompletedEventSink: FlutterEventSink?
    var audioPlayer: AudioSpectrumPlayer!
    var isPlaying: Bool = false

    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "flutter_spectrum", binaryMessenger: registrar.messenger())
        let instance = FlutterSpectrumPlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
        
        // 分别设置两个EventChannel的StreamHandler
        let spectrumEventChannel = FlutterEventChannel(name: "flutter_spectrum.events", binaryMessenger: registrar.messenger())
        spectrumEventChannel.setStreamHandler(SpectrumStreamHandler(plugin: instance))
        
        let playCompleteChannel = FlutterEventChannel(name: "flutter_spectrum.play.complete", binaryMessenger: registrar.messenger())
        playCompleteChannel.setStreamHandler(PlayCompleteStreamHandler(plugin: instance))
    }

    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        switch call.method {
        case "startPlay":
            if let args = call.arguments as? [String: Any],
               let filePath = args["filePath"] as? String {
                startPlay(filePath: filePath)
                result(nil)
            } else {
                result(FlutterError(code: "INVALID_ARGUMENTS", message: "fileName is required", details: nil))
            }
        case "stopPlay":
            stopAudio()
            result(nil)
        default:
            result(FlutterMethodNotImplemented)
        }
    }

    public func stopAudio() {
        isPlaying = false
        audioPlayer?.stop()
        audioPlayer = nil
    }

    public func startPlay(filePath: String) {
        isPlaying = true
        audioPlayer = AudioSpectrumPlayer(bufferSize: 1024)
        audioPlayer.delegate = self
        audioPlayer.play(withFilePath: filePath)
    }

    func player(_ player: AudioSpectrumPlayer, didGeneratePCMData data: [Float]) {
        guard isPlaying else { return } // 如果未播放，则不发送数据

        let pcmData = data.map { Double($0) }
        DispatchQueue.main.async { [weak self] in
            self?.eventSink?(pcmData)
        }
    }

    func playCompleted(_ player: AudioSpectrumPlayer) {
        isPlaying = false
        DispatchQueue.main.async { [weak self] in
            // 发送到播放完成专用的eventSink
            self?.playCompletedEventSink?(nil)
        }
    }
}

// 处理频谱数据的StreamHandler
class SpectrumStreamHandler: NSObject, FlutterStreamHandler {
    weak var plugin: FlutterSpectrumPlugin?

    init(plugin: FlutterSpectrumPlugin) {
        self.plugin = plugin
    }

    func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        plugin?.eventSink = events // 设置频谱数据的sink
        return nil
    }

    func onCancel(withArguments arguments: Any?) -> FlutterError? {
        plugin?.eventSink = nil
        return nil
    }
}

// 处理播放完成的StreamHandler
class PlayCompleteStreamHandler: NSObject, FlutterStreamHandler {
    weak var plugin: FlutterSpectrumPlugin?

    init(plugin: FlutterSpectrumPlugin) {
        self.plugin = plugin
    }

    func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        plugin?.playCompletedEventSink = events // 设置播放完成的sink
        return nil
    }

    func onCancel(withArguments arguments: Any?) -> FlutterError? {
        plugin?.playCompletedEventSink = nil
        return nil
    }
}
